package com.mydemo.common.exception.handler;

import com.mydemo.common.exception.captcha.CaptchaException;
import com.mydemo.common.exception.user.UserException;
import com.mydemo.common.pojo.RespResult;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;

/**
 * 全局异常处理器
 * @author Last_Island
 * @version 1.0
 */
//@Component
@RestControllerAdvice()
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限异常处理
     */
    @ExceptionHandler(AccessDeniedException.class)
    public RespResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI,e.getMessage());
        return RespResult.error(403, "没有权限，请联系管理员授权");
    }

    /**
     * 认证异常处理
     */
    @ExceptionHandler(UserException.class)
    public RespResult handleUserException(UserException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',登录失败'{}'", requestURI, e.getMessage());
        return RespResult.error(401, e.getMessage());
    }

    /**
     * 验证码异常处理
     */
    @ExceptionHandler(CaptchaException.class)
    public RespResult handleCaptchaException(CaptchaException e, HttpServletRequest request)
    {
        log.error("验证码错误'{}'", e.getMessage());
        return RespResult.error(405, e.getMessage());
    }

    /**
     * 其他异常处理
     */
    @ExceptionHandler(Exception.class)
    public RespResult handleException(Exception e, HttpServletRequest request,  HandlerMethod handlerMethod) {
        String requestURI = request.getRequestURI();
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBeanType().getName();
        log.error("请求地址'{}',异常方法'{}' 发生异常'{}'", requestURI, className+'.'+methodName, e.getMessage());
        return RespResult.error(500, "操作失败",e.getMessage());
    }
}
